package com.example.xpagedemoproject.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.xpagedemoproject1.R;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xpage.utils.TitleBar;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = "数据接收",params = {DataReceiveFragment.KEY_IS_NEED_BACK,DataReceiveFragment.KEY_EVENT_NAME,DataReceiveFragment.KEY_EVENT_DATA})
public class DataReceiveFragment extends XPageFragment {
    public final static String KEY_IS_NEED_BACK = "is_need_back";
    public final static String KEY_EVENT_NAME = "event_name";
    public final static String KEY_EVENT_DATA = "event_data";
    public final static String KEY_BACK_DATA = "back_data";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    Button btnBack;

    @AutoWired(name = KEY_IS_NEED_BACK)
    boolean isNeedBack;
    @AutoWired(name = KEY_EVENT_DATA)
    String eventData;
    @AutoWired(name = KEY_EVENT_NAME)
    String eventName;

    int number = 1000;
    boolean isChanged;

    @Override
    protected TitleBar initTitleBar() {
        TitleBar titleBar = super.initTitleBar();
        titleBar.addAction(new TitleBar.TextAction("变化") {
            @Override
            public void performAction(View view) {
                number = (int) (Math.random() * 1000);
                update();
            }
        });
        return titleBar;
    }

    private void update() {
        tvTitle.setText(String.format("接收到数据\n 事件名：%s\n 事件数据：%s\n 数字：%d", eventName, eventData, number));
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        XRouter.getInstance().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_data_receive;
    }

    @Override
    protected void initViews() {
        update();
        if (isNeedBack) {
            btnBack.setVisibility(View.VISIBLE);
        }else{
            btnBack.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListeners() {

    }

    @Override
    public void onSaveInstanceState(@Nullable Bundle outState){
        super.onSaveInstanceState(outState);
        isChanged = true;
    }

    @OnClick(R.id.btn_back)
    protected void onViewClicked(View view){
        Intent intent = new Intent();
        intent.putExtra(KEY_EVENT_DATA,"==【返回的数据】==");
        setFragmentResult(500,intent);
        popToBack();
    }
}
